$( document ).ready(function() {
	$("#remoteCall").live("click", function() {
		cleanText();
		if (doCheck()) {
//			doReplace();

			var start = new Date().getTime();
			$("#remoteCallForm").ajaxSubmit({
				async: false,
				success: function(data){
					var end = new Date().getTime() - start;
					$("#infoMsg").text("success!   用时: " + end + "ms");

//					var result = "";
//					result = appendResult(data, result, "", "\n");
//					result = $.toJSONString(data);
					$("#results").text(data);
				},
				error:function(result){
					$("#errorMsg").text("fail");
				}
			});
		}
	});

	$("#methodSelect").live("change", function() {
		$("#method").val($(this).val());
		$("#loadArgsFormMethod").val($(this).val());
		cleanText();
	});

	$(".radio-inline input").live("click", function() {
		$("#isPaddedBy").val($(this).val());
	});

	$("#remoteCallForm .form-control").live("change", function() {
		cleanText();
	});

	var argIndex = 1;
	$("#add-args").live("click", function() {
		var args = $("#append-args").clone(true);
		args.removeAttr("id");
		args.find(".argTypes").attr("name", "argTypes" + argIndex);
		args.find(".arguments").attr("name", "arguments" + argIndex);
		$("#generic-args").append(args);
		argIndex++;

		cleanText();
	});

	$("#delete-args").live("click", function() {
		$(this).parents(".append-args").remove();
		cleanText();
	});

	function cleanText() {
		$("#infoMsg").text("");
		$("#errorMsg").text("");
		$("#remoteCallForm .form-control").each(function() {
			if (! ($(this).val() === "" || $(this).val() === undefined)) {
				$(this).css("border", "1px solid #ccc");
			}
		});
	}

	function doCheck() {
		var flag = true;
		$("#remoteCallForm .form-control").each(function() {
			if ($(this).val() === "" || $(this).val() === undefined) {
				$(this).css("border", "1px solid #e38d13");
				$("#errorMsg").text("All fields are required!");
				flag = false;
			}
		});
		return flag;
	}

//	function doReplace() {
//		$("#generic-args .arguments").each(function() {
//			$(this).next().val($(this).val().replace(/,/g, "###"));
//		});
//	}

//	function appendResult(data, result, before, end) {
//		$.each(data, function(name, value) {
//			if (value != '' && value != null && value != undefined && value.toString().indexOf('[object Object]') >= 0) {
//				result += before + name + ":" + end;
//				result = appendResult(value, result, before + "\t", end);
//			} else {
//				result += before + name + ": " + value + end;
//			}
//		});
//		return result;
//	}
	
	
	/**
	 * download dubbo rest parameters
	 */
	$("#downloadParam").live("click", function () {
		var content = getParamsXML();
		var fileName = $("#service").val() + "." + $("#method").val() + ".xml";
		saveFile(fileName, content);
	});

	function getParamsXML() {
		var content = "<?xml version='1.0' encoding='UTF-8'?>\n";
		content += "<invocation>\n";
		$("#remoteCallForm .form-control").each(function() {
			var id = $(this).attr("id");
			if (id === "service" || id === "method" || id === "isPassedBy") {
				content += "\t<" + id + ">" + $(this).val() + "</" + id + ">\n";
			}
		});

		if ($("#generic-args .append-args").size() > 0) {
			content += "\t<args>\n";
			$("#generic-args .append-args").each(function() {
				content += "\t\t<arg>\n";
				content += "\t\t\t<argType>" + $(this).find(".argTypes").val() + "</argType>\n";
				content += "\t\t\t<argument>" + $(this).find(".arguments").val() + "</argument>\n";
				content += "\t\t</arg>\n";
			});
			content += "\t</args>\n";
		}
		content += "</invocation>\n";

		return content;
	}

	function saveFile(fileName, content) {
		var BB = self.Blob;
        saveAs(
          new BB(
              [content]
            , { type: "text/plain;charset=utf8" }
        ) , fileName);
	}

//	function getParamsJSON() {
//		var content = {};
//		$("#remoteCallForm .form-control").each(function() {
//			var id = $(this).attr("id");
//			if (id === "zkAddress" || id === "service" || id === "method" || id === "isPassedBy") {
//				content[id] = $(this).val();
//			}
//		});
//
//		var args = [];
//		$("#generic-args .append-args").each(function() {
//			var arg = {};
//			arg[$(this).find(".argTypes").val()] = $(this).find(".arguments").val();
//			args.push(arg);
//		});
//		content["args"] = args;
//		return $.toJSONString(content);
//	}

//	function downloadFile(fileName, content){
//	    var aLink = document.createElement('a');
//	    var blob = new Blob([content]);
//	    var evt = document.createEvent("HTMLEvents");
//	    evt.initEvent("click", false, false);
//	    aLink.download = fileName;
//	    aLink.href = URL.createObjectURL(blob);
//	    aLink.dispatchEvent(evt);
//	}

	/**
	 * upload parameters file
	 */
	$("#uploadFile").live("change", function () {
		cleanText();
		if (this.value !== "" && this.value !== undefined) {
			$("#uploadForm").submit();
		}
	});

	/**
	 * to save arguments to zookeeper
	 */
	$("#toSaveArgs").live("click", function() {
		if (doCheck()) {
			$(this).modal.toggle($(this));

			var dom = "";
			$("#remoteCallForm .form-control").each(function() {
				var id = $(this).attr("id");
				if (id === "service" || id === "method" || id === "isPassedBy") {
					dom += "<input type='hidden' name='" + id + "' value='" + $(this).val() + "'>";
				}
			});

			$("#generic-args .append-args").each(function() {
				dom += "<input type='hidden' name='" + $(this).find(".argTypes").attr("name") + "' value='" + $(this).find(".argTypes").val() + "'>";
				dom += "<input type='hidden' name='" + $(this).find(".arguments").attr("name") + "' value='" + $(this).find(".arguments").val() + "'>";
			});

			$("#zkParams #hiddenParams").empty().append(dom);
		}
	});

	/**
	 * save arguments to zookeeper
	 */
	$("#saveArgs").live("click", function() {
		if ($("#zkParams #argName").val() === "" || $("#zkParams #argName").val() === undefined) {
			$("#zkParams #argName").css("border", "1px solid #e38d13");
		} else {
//			Modal.hide($("#saveArgsToZk"));
//			$("#saveArgsToZk").removeClass('in')
//				.off('click.dismiss.bs.modal')
//				.off('mouseup.dismiss.bs.modal');

			$("#zkParams").ajaxSubmit({
				async: false,
				success: function(data){
					$("#infoMsg").text(data);
				},
				error:function(result){
					$("#errorMsg").text("fail");
				}
			});
		}
	});

	/**
	 * show load arguments from zookeeper
	 */
	$("#toChooseArgs").live("click", function() {
		if ($("#loadArgsFormMethod").val() === "" || $("#loadArgsFormMethod").val() === undefined) {
			$("#methodSelect").css("border", "1px solid #e38d13");
			$("#errorMsg").text("请先选择方法!");
		} else {
			$("#loadArgsForm").ajaxSubmit({
				async: false,
				success: function(data){
//					$("#results").text(data);

					var argDom = "";
					var defaultRedirect = $("#defaultRedirect").val();
					var argNames = data.split("###");
					for (var index in argNames) {
						if (argNames[index] !== "\n" && argNames[index] !== "") {
							argDom += "<tr><td><a href='" + defaultRedirect + "?argName=" + argNames[index]
								+ "&method=" + $("#method").val() + "' class='col-md-10'>" + argNames[index] + "</a>"
								+ "<span class='deleteArgName' data='" + argNames[index] + "'>×</span></td></tr>";
						}
					}

					if (argDom.length === 0) {
						$("#errorMsg").text("没有保存的参数供选择!");
					} else {
						$("#loadArgsFromZk .modal-body .table").empty().append(argDom);
						$("#toChooseArgs").modal.toggle($("#toChooseArgs"));
					}
				},
				error:function(result){
				}
			});
		}
	});

	$(".deleteArgName").live("click", function() {
		var _this = $(this);
		$.ajax({
			url: $("#defaultRedirect").val() + "/deleteArgName",
			type: "POST",
			data: {method: $("#method").val(),
					argName: _this.attr("data")
				},
			success: function(data) {
				if (data.indexOf("操作成功") > 0) {
					_this.parents("tr").remove();
				} else {
					$("#deleteArgError").text("删除失败！");
					setTimeout(function() {$("#deleteArgError").text("");}, 2000);
				}
			},
			error: function() {
				$("#deleteArgError").text("删除失败！");
			}
		});
	});

});